﻿// -------------------------------------------------------------------------------------------------------------------------------
// <copyright file="CrcsSparseSymmetricMatrixExtensions.cs" company="Exul">
//     Copyright (c) Exul. All rights reserved.
// </copyright>
// <author>
//     Exul
// </author>
// -------------------------------------------------------------------------------------------------------------------------------

namespace ExulLibrary.Mathematics.LinearAlgebra.Sequential
{
    #region Usings

    using System;

    using ExulLibrary.Exceptions;
    using ExulLibrary.Mathematics.LinearAlgebra.Exceptions;

    #endregion

    /// <summary>
    ///     Provides extension methods for <see cref="CrcsSparseSymmetricMatrix{T}"/>.
    /// </summary>
    public static class CrcsSparseSymmetricMatrixExtensions
    {
        #region Methods

        #region public

        /// <summary>
        ///     Sets the default value to all elements of the matrix.
        /// </summary>
        /// <typeparam name="T">
        ///     The type of values of matrix elements.
        /// </typeparam>
        /// <param name="matrix">
        ///     The matrix that contains elements to clear.
        /// </param>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="matrix"/> is <see langword="null"/>.
        /// </exception>
        public static void Clear<T>(this CrcsSparseSymmetricMatrix<T> matrix)
        {
            #if SAFE

            if (matrix == null)
            {
                throw new ArgumentNullException("matrix");
            }

            #endif

            Array.Clear(
                matrix.TriangleValues, matrix.Begins[0], matrix.Begins[matrix.RowsCount] - matrix.Begins[0]);
            Array.Clear(matrix.DiagonalValues, 0, matrix.RowsCount);
        }

        /// <summary>
        ///     Sets the default value to all elements in the specified column of the matrix.
        /// </summary>
        /// <typeparam name="T">
        ///     The type of values of matrix elements.
        /// </typeparam>
        /// <param name="matrix">
        ///     The matrix that contains the column to clear.
        /// </param>
        /// <param name="columnIndex">
        ///     The zero-based index of the column to clear.
        /// </param>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="matrix"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="ElementIndexIsOutOfRangeException">
        ///     <paramref name="columnIndex"/> is negative or greater than or equal to columns count.
        /// </exception>
        public static void ClearColumn<T>(this CrcsSparseSymmetricMatrix<T> matrix, int columnIndex)
        {
            #if SAFE

            if (matrix == null)
            {
                throw new ArgumentNullException("matrix");
            }

            if ((columnIndex < 0) || (matrix.ColumnsCount <= columnIndex))
            {
                throw new ElementIndexIsOutOfRangeException("columnIndex", columnIndex, 0, matrix.ColumnsCount - 1);
            }

            #endif

            ClearRowColumn(matrix, columnIndex);
        }

        /// <summary>
        ///     Sets the default value to all elements in the specified row of the matrix.
        /// </summary>
        /// <typeparam name="T">
        ///     The type of values of matrix elements.
        /// </typeparam>
        /// <param name="matrix">
        ///     The matrix that contains the row to clear.
        /// </param>
        /// <param name="rowIndex">
        ///     The zero-based index of the row to clear.
        /// </param>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="matrix"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="ElementIndexIsOutOfRangeException">
        ///     <paramref name="rowIndex"/> is negative or greater than or equal to rows count.
        /// </exception>
        public static void ClearRow<T>(this CrcsSparseSymmetricMatrix<T> matrix, int rowIndex)
        {
            #if SAFE

            if (matrix == null)
            {
                throw new ArgumentNullException("matrix");
            }

            if ((rowIndex < 0) || (matrix.RowsCount <= rowIndex))
            {
                throw new ElementIndexIsOutOfRangeException("rowIndex", rowIndex, 0, matrix.RowsCount - 1);
            }

            #endif

            ClearRowColumn(matrix, rowIndex);
        }

        /// <summary>
        ///     Creates a deep copy of the matrix.
        /// </summary>
        /// <typeparam name="T">
        ///     The type of values of matrix elements.
        /// </typeparam>
        /// <param name="source">
        ///     The source matrix.
        /// </param>
        /// <returns>
        ///     A deep copy of the matrix.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="source"/> is <see langword="null"/>.
        /// </exception>
        public static CrcsSparseSymmetricMatrix<T> Clone<T>(this CrcsSparseSymmetricMatrix<T> source)
        {
            #if SAFE

            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            #endif

            var result = new CrcsSparseSymmetricMatrix<T>(source.Begins, source.Indexes);
            Array.Copy(source.DiagonalValues, result.DiagonalValues, result.DiagonalValues.Length);
            Array.Copy(source.TriangleValues, result.TriangleValues, result.TriangleValues.Length);
            return result;
        }

        /// <summary>
        ///     Gets the element in the matrix at the specified location.
        /// </summary>
        /// <typeparam name="T">
        ///     The type of values of matrix elements.
        /// </typeparam>
        /// <param name="matrix">
        ///     The matrix that contains the element to get.
        /// </param>
        /// <param name="rowIndex">
        ///     The zero-based index of row of the element to get.
        /// </param>
        /// <param name="columnIndex">
        ///     The zero-based index of column of the element to get.
        /// </param>
        /// <returns>
        ///     The element in the matrix at the specified location.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="matrix"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="ElementIndexIsOutOfRangeException">
        ///     <paramref name="rowIndex"/> is negative or greater than or equal to
        ///     the number of rows of <paramref name="matrix"/>.
        ///     <para>--or--</para>
        ///     <para>
        ///         <paramref name="columnIndex"/> is negative or greater than or equal to
        ///         the number of columns of <paramref name="matrix"/>.
        ///     </para>
        /// </exception>
        public static T GetAt<T>(this CrcsSparseSymmetricMatrix<T> matrix, int rowIndex, int columnIndex)
        {
            #if SAFE

            if (matrix == null)
            {
                throw new ArgumentNullException("matrix");
            }

            if ((rowIndex < 0) || (matrix.RowsCount <= rowIndex))
            {
                throw new ElementIndexIsOutOfRangeException("rowIndex", rowIndex, 0, matrix.RowsCount - 1);
            }

            if ((columnIndex < 0) || (matrix.ColumnsCount <= columnIndex))
            {
                throw new ElementIndexIsOutOfRangeException("columnIndex", columnIndex, 0, matrix.ColumnsCount - 1);
            }

            #endif

            if (rowIndex == columnIndex)
            {
                return matrix.DiagonalValues[rowIndex];
            }

            if (rowIndex < columnIndex)
            {
                var temp = rowIndex;
                rowIndex = columnIndex;
                columnIndex = temp;
            }

            var columnsIndexes = matrix.Indexes;

            var elementIndex = matrix.Begins[rowIndex];
            var rowEnd = matrix.Begins[rowIndex + 1];
            while ((elementIndex < rowEnd) && (columnsIndexes[elementIndex] < columnIndex))
            {
                elementIndex++;
            }

            // if element is found, return it; otherwise, return default value for T type
            return (elementIndex == rowEnd) || (columnsIndexes[elementIndex] != columnIndex)
                       ? default(T)
                       : matrix.TriangleValues[elementIndex];
        }

        /// <summary>
        ///     Sets the element in the matrix at the specified location.
        /// </summary>
        /// <typeparam name="T">
        ///     The type of values of matrix elements.
        /// </typeparam>
        /// <param name="matrix">
        ///     The matrix that contains the element to set.
        /// </param>
        /// <param name="newValue">
        ///     The new value for the element.
        /// </param>
        /// <param name="rowIndex">
        ///     The zero-based index of row of the element to set.
        /// </param>
        /// <param name="columnIndex">
        ///     The zero-based index of column of the element to set.
        /// </param>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="matrix"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="ElementIndexIsOutOfRangeException">
        ///     <paramref name="rowIndex"/> is negative or greater than or equal to
        ///     the number of rows of <paramref name="matrix"/>.
        ///     <para>
        ///         --or--
        ///     </para>
        ///     <para>
        ///         <paramref name="columnIndex"/> is negative or greater than or equal to
        ///         the number of columns of <paramref name="matrix"/>.
        ///     </para>
        /// </exception>
        /// <exception cref="ReadOnlyMatrixElementException">
        ///     <paramref name="rowIndex"/> and <paramref name="columnIndex"/> specifies the element
        ///     that is not in the portrait of <paramref name="matrix"/>.
        /// </exception>
        public static void SetAt<T>(this CrcsSparseSymmetricMatrix<T> matrix, T newValue, int rowIndex, int columnIndex)
        {
            #if SAFE

            if (matrix == null)
            {
                throw new ArgumentNullException("matrix");
            }

            if ((rowIndex < 0) || (matrix.RowsCount <= rowIndex))
            {
                throw new ElementIndexIsOutOfRangeException("rowIndex", rowIndex, 0, matrix.RowsCount - 1);
            }

            if ((columnIndex < 0) || (matrix.ColumnsCount <= columnIndex))
            {
                throw new ElementIndexIsOutOfRangeException("columnIndex", columnIndex, 0, matrix.ColumnsCount - 1);
            }

            #endif

            if (rowIndex == columnIndex)
            {
                matrix.DiagonalValues[rowIndex] = newValue;
                return;
            }

            if (rowIndex < columnIndex)
            {
                var temp = rowIndex;
                rowIndex = columnIndex;
                columnIndex = temp;
            }

            var columnsIndexes = matrix.Indexes;

            var elementIndex = matrix.Begins[rowIndex];
            var rowEnd = matrix.Begins[rowIndex + 1];
            while ((elementIndex < rowEnd) && (columnsIndexes[elementIndex] < columnIndex))
            {
                elementIndex++;
            }

            if ((elementIndex == rowEnd) || (columnsIndexes[elementIndex] != columnIndex))
            {
                #if SAFE

                throw new ReadOnlyMatrixElementException("matrix", rowIndex, columnIndex);

                #else

                return;

                #endif
            }

            matrix.TriangleValues[elementIndex] = newValue;
        }

        #endregion

        #region private

        /// <summary>
        ///     Sets the default value to all elements in the specified row and column of the matrix.
        /// </summary>
        /// <typeparam name="T">
        ///     The type of values of matrix elements.
        /// </typeparam>
        /// <param name="matrix">
        ///     The matrix that contains the row and the column to clear.
        /// </param>
        /// <param name="rowColumnIndex">
        ///     The zero-based index of the row and the column to clear.
        /// </param>
        private static void ClearRowColumn<T>(CrcsSparseSymmetricMatrix<T> matrix, int rowColumnIndex)
        {
            var begins = matrix.Begins;
            var indexes = matrix.Indexes;
            var values = matrix.TriangleValues;
            var rowsCount = matrix.RowsCount;

            matrix.DiagonalValues[rowColumnIndex] = default(T);

            Array.Clear(values, begins[rowColumnIndex], begins[rowColumnIndex + 1] - begins[rowColumnIndex]);

            if (rowsCount - 1 <= rowColumnIndex)
            {
                return;
            }

            var rowEnd = begins[rowColumnIndex + 1];

            for (var rowIndex = rowColumnIndex + 1; rowIndex < rowsCount; rowIndex++)
            {
                var elementIndex = rowEnd;
                rowEnd = begins[rowIndex + 1];
                while ((elementIndex < rowEnd) && (indexes[elementIndex] < rowColumnIndex))
                {
                    elementIndex++;
                }

                if ((elementIndex < rowEnd) && (indexes[elementIndex] == rowColumnIndex))
                {
                    values[elementIndex] = default(T);
                }
            }
        }

        #endregion

        #endregion
    }
}